﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;

namespace TravelSite.Admin
{
    public partial class UserManagement : BaseDataPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCombo();
                LoadData();
            }
        }

        private void LoadCombo()
        {
            using (var repo = RepositoryFactory.ResolveRepository<EmailSettingRepository>())
            {
                ddlEmailSettingId.DataSource = repo.EmailSettingsCombo(false, false);
                ddlEmailSettingId.DataBind();
                ddlEmailSettingId.SelectedValue = repo.Find().EmailSettingId.ToString();
            }
        }

        public override void LoadData()
        {
            using (var userRepo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                gridUsers.DataSource = userRepo.Search(txtLastNameFilter.Text, txtEmailFilter.Text, ddlIsAdminFilter.SelectedItem.Text, ddlIsActiveFilter.SelectedItem.Text);
                gridUsers.DataBind();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        protected void upUserDetails_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["__EVENTTARGET"]))
                if (Request["__EVENTTARGET"] != upUserDetails.ClientID)
                    return;

            if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
            {
                hdUserId.Text = Request["__EVENTARGUMENT"];
                LoadCombo();
                if (hdUserId.Text != "-1")
                {
                    using (var userRepo = RepositoryFactory.ResolveRepository<UserRepository>())
                    {
                        lblDialogTitle.Text = "Edit User";
                        User usr = userRepo.Find(Convert.ToInt32(hdUserId.Text));
                        txtFirstName.Text = usr.FirstName;
                        txtLastName.Text = usr.LastName;
                        txtUserName.Text = usr.UserName;
                        txtEmail.Text = usr.Email;
                        if (usr.EmailSettingId.HasValue)
                            ddlEmailSettingId.SelectedValue = usr.EmailSettingId.Value.ToString();
                        ddlAccessLevel.SelectedValue = usr.IsAdmin ? "1" : "0";
                        lnkChangePassword.Visible = true;
                        cbActive.Checked = usr.StatusName == "Active";
                        lnkChangePassword.Attributes.Add("onclick", string.Format("javascript:showPasswordChange({0});", hdUserId.Text));
                    }
                }
                else
                {
                    lblDialogTitle.Text = "Add New User";
                    txtFirstName.Text = "";
                    txtLastName.Text = "";
                    txtUserName.Text = "";
                    txtEmail.Text = "";
                    cbActive.Checked = true;
                    ddlAccessLevel.SelectedValue = "1";
                    lnkChangePassword.Visible = false;
                }
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowEdit", "$('#userDialog').dialog('open');", true);
            }
        }

        protected void gridUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridUsers.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void btnSaveUser_Click(object sender, EventArgs e)
        {
            if (hdUserId.Text == "-1")
            {
                var user = Membership.GetUser(txtUserName.Text);
                if (user != null)
                {
                    JsCodeToRunOnReady = "$('#userDialog').dialog('open'); alert('User Name already exists!');";
                    return;
                }

                if (Membership.GetUserNameByEmail(txtEmail.Text) != null)
                {
                    JsCodeToRunOnReady = "$('#userDialog').dialog('open'); alert('Email already exists!');";
                    return;
                }
            }

            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                User usr;

                if (hdUserId.Text == "-1")
                {
                    usr = new User();
                    AssignUserValues(usr);

                    string pwd = Guid.NewGuid().ToString().Split(new char[] { '-' })[0];
                    repo.AddManual(usr, pwd);
                    usr = repo.Find(usr.UserName);

                    lbldetailDialog.Text = "User added";
                    UserNameDetail_text.Text = string.Format("Username: {0}", txtUserName.Text);
                    UserPasswordDetail_text.Text = string.Format("Password: {0}", pwd);
                    JsCodeToRunOnReady = "$('#detailDialog').dialog('open');";
                }
                else
                {
                    usr = repo.Find(Convert.ToInt32(hdUserId.Text));
                    AssignUserValues(usr);

                    string result = repo.Update(usr);
                    if (!string.IsNullOrEmpty(result))
                    {
                        JsCodeToRunOnReady = string.Format("$('#userDialog').dialog('open'); alert('{0}');", result);
                        return;
                    }
                }

                if (cbActive.Checked)
                {
                    repo.Activate(usr.Id);
                }
                else
                {
                    repo.Deactivate(usr.Id);
                }
            }

            LoadData();
        }

        void AssignUserValues(User usr)
        {
            usr.LastName = txtLastName.Text;
            usr.FirstName = txtFirstName.Text;
            usr.Email = txtEmail.Text;
            usr.UserName = txtUserName.Text;
            usr.IsAdmin = (ddlAccessLevel.SelectedValue == "1");
            usr.EmailSettingId = ddlEmailSettingId.SelectedValue == "-1" ? (int?)null : Convert.ToInt32(ddlEmailSettingId.SelectedValue);
        }

        protected void btnSavePassword_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                User usr = repo.Find(Convert.ToInt32(hdUserId1.Value));
                if (usr == null) return;

                MembershipUser u = Membership.GetUser(usr.UserName);
                u.ChangePassword(usr.Password, tbPassword.Text);

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "HideChange", "$('#passwordDialog').dialog('close'); alert('Password changed!');", true);
            }
        }

        protected void Users_Command(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                switch (e.CommandName)
                {
                    case "deactivate":
                        repo.Deactivate(id);
                        break;
                    case "activate": 
                        repo.Activate(id);
                        break;
                    case "delete":
                        repo.Delete(id);
                        break;
                }
            }
            LoadData();
        }

        protected void gridUsers_PreRender(object sender)
        {
            gridUsers.HeaderRow.TableSection = TableRowSection.TableHeader;
        }

        public bool asd(string sd)
        {
            return false;
        }
    }
}